<template>
  <el-button type="success" @click="add">新增用户</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>
  <el-table
      :inline="true"
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection"/>
    <el-table-column type="index" label="序号"/>
    <el-table-column property="loginAct" label="账号" width="170px"/>
    <el-table-column property="name" label="姓名" width="170px"/>
    <el-table-column property="phone" label="手机"/>
    <el-table-column property="email" label="邮箱"/>
    <el-table-column property="createTime" label="创建时间" />
    <el-table-column label="操作" width="250px">
      <template #default="scope">
<!--        作用域插槽，可以拿到作用域的相关信息，scope.row通过这个方式可以获得行的数据，然后取id-->
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
<!--  分页条-->
  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"
  />

<!--新增用户对话框-->
  <el-dialog
      v-model="userDialogOverflowVisible"
      :title="userQuery.id>0 ? '编辑用户':'新增用户'"
      width="600"
      draggable
      overflow
      center
  >

    <el-form ref="userRefFrom" :model="userQuery" :rules="userRules" label-position="left" label-width="110px">
<!--      label-width="60px"距离左侧的空白部分-->
      <el-form-item label="账号" prop="loginAct">
        <el-input placeholder="请输入账号" v-model="userQuery.loginAct" />
      </el-form-item>

      <el-form-item label="密码" v-if="userQuery.id > 0"><!-- 编辑 -->
        <el-input type="password"  placeholder="请输入6到16位的密码" show-password v-model="userQuery.loginPwd" />
      </el-form-item>

      <el-form-item label="密码" prop="loginPwd" v-else><!-- 新增 -->
        <el-input type="password"  placeholder="请输入6到16位的密码" show-password v-model="userQuery.loginPwd" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input placeholder="请输入中文用户名" v-model="userQuery.name" />
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input placeholder="请输入手机号" v-model="userQuery.phone" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入邮箱地址" v-model="userQuery.email" />
      </el-form-item>

      <el-form-item label="账号未过期" prop="accountNoExpired">
        <el-select v-model="userQuery.accountNoExpired" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >
            <!-- key是vue里提升循环效率 -->
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="密码未过期" prop="credentialsNoExpired">
        <el-select v-model="userQuery.credentialsNoExpired" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          >
            <!-- key是vue里提升循环效率 -->
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="账号未锁定" prop="accountNoLocked">
        <el-select v-model="userQuery.accountNoLocked" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          >
            <!-- key是vue里提升循环效率 -->
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否启用" prop="accountEnabled">
        <el-select v-model="userQuery.accountEnabled" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          >
            <!-- key是vue里提升循环效率 -->
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userDialogOverflowVisible = false">关闭</el-button>
        <el-button type="primary" @click="userSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {doDelete, doGet, doPost, doPut, messageConfirm} from "../http/httpRequest.js";
import {messageTip, removeToken} from "../util/util.js";

export default {
  name: "UserView",
  //注入父级页面提供的所有属性，函数，对象等
  inject: ['reload'],
  data() {
    return {//return是为了双向绑定起作用，需要的值已经通过请求返回到了参数中了，通过return返回到页面上的相应位置
      //用户列表数据，初始值为空
      userList : [{}],
      pageSize: 0,
      total: 0,
      //新增用户的弹窗是否弹出的控制参数，false不弹出，true弹出
      userDialogOverflowVisible: false,
      //定义用户表单对象，初始值空
      userQuery: {},
      //定义用户验证规则
      userRules : {
        loginAct : [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        loginPwd : [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur' }
        ],
        name : [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { pattern: /^[\u4E00-\u9FA5]{1,5}$/, message: '姓名必须是中文', trigger: 'blur'}
        ],
        phone : [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern : /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur'}
        ],
        email : [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern : /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式有误', trigger: 'blur'}
        ],
        accountNoExpired : [
          { required: true, message: '请选择账号是否未过期', trigger: 'blur' },
        ],
        credentialsNoExpired : [
          { required: true, message: '请选择密码是否未过期', trigger: 'blur' },
        ],
        accountNoLocked : [
          { required: true, message: '请选择账号是否未未锁定', trigger: 'blur' },
        ],
        accountEnabled : [
          { required: true, message: '请选择账号是否可用', trigger: 'blur' },
        ]
      },
      //下拉选项数组
      options : [
        {label : '是',value : 1},
        {label : '否',value : 0},
      ],
      //用户id的数组
      userIdArray : []
    }
  },
  mounted() {//钩子函数，就是实现调用一些不是通过事件来驱动的方法而生的
    this.getData(1);
  },
  methods: {
    //勾选或者取消勾选时，触发该函数
    handleSelectionChange(selectionDataArray) {
      this.userIdArray = [];
      selectionDataArray.forEach(data => {
        let userId = data.id;
        this.userIdArray.push(userId);
      })
    },
    //查询用户列表数据
    getData(current) {
      doGet("/api/users",{
        current : current //当前查询第几页
      }).then( resp => {
        if (resp.data.code === 200) {
          this.userList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      })
    },
    //分页函数(current是element组件传过来的，就是传当前页码)
    toPage(current) {
      this.getData(current);
    },
    //详情函数
    view(id) {
      //跳转到/dashboard/user/1的路由上   $route -> 获取当前路由对应的属性信息，如.path拿到路径 .params.id拿到参数  $router -> 调用当前路由的方法，如.push(/./)跳转到指定路由地址 .go(-1)跳转到上一个路由地址
      this.$router.push("/dashboard/user/" + id);
    },
    //新增用户，打开填写的对话框
    add() {
      this.userQuery = {};
      this.userDialogOverflowVisible = true;
    },
    //新增用户提交保存
    userSubmit() {
      let formData = new FormData();
      for (let field in this.userQuery) {
        formData.append(field,this.userQuery[field]);
      }
      this.$refs.userRefFrom.validate( (isValid) => {
        if (isValid) {

          if (this.userQuery.id > 0) {/*编辑*/
            doPut("/api/user", formData).then( resp => {
              if (resp.data.code === 200){
                messageTip("编辑用户提交成功","success");
                //页面刷新
                this.reload();
              } else {
                messageTip("编辑用户提交失败","error");
              }
            })
          } else {/*新增*/
            doPost("/api/user", formData).then( resp => {
              if (resp.data.code === 200){
                messageTip("新增用户提交成功","success");
                //页面刷新
                this.reload();
              } else {
                messageTip("新增用户提交失败","error");
              }
            })
          }
        }
      })
    },
    //编辑用户信息
    edit(id) {
      this.userDialogOverflowVisible = true;
      this.loadUser(id);
    },
    //加载用户信息
    loadUser(id) {
      doGet("/api/user/" + id, {}).then(resp => {
        if (resp.data.code === 200){
          this.userQuery = resp.data.data;
          this.userQuery.loginPwd = "";
        }
      })
    },
    //删除用户信息
    del(id) {
      messageConfirm("您确定要删除该数据吗？").then(() => {//用户点确定触发then函数
        doDelete("/api/user/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除成功","success");
            this.reload();
          } else {
            messageTip("删除失败，原因：" + resp.data.msg,"error");
          }
        })
      })
          .catch(() => {//点取消触发catch函数
            messageTip("已为您取消","warning");
          })
    },
    //批量删除信息
    batchDel(id) {
      if (this.userIdArray.length <= 0) {
        //提示一下
        messageConfirm("还未选择删除数据","warning");
        return;
      }
      messageConfirm("您确定要删除选中数据吗？").then(() => {//用户点确定触发then函数
        //原来是数组[1,2,3],通过join方法可变成"1,2,3"的字符串
        let ids = this.userIdArray.join(",")
        doDelete("/api/user", {
          ids : ids
        }).then(resp => {
          if (resp.data.code === 200) {
            messageTip("批量删除成功","success");
            this.reload();
          } else {
            messageTip("批量 删除失败，原因：" + resp.data.msg,"error");
          }
        })
      })
          .catch(() => {//点取消触发catch函数
            messageTip("已为您取消","warning");
          })
    },
  }
}
</script>

<style scoped>
. el-table {
  margin-top: 12px;
}
. el-pagination {
    margin-top: 12px;
  }
</style>